import uuid
import itertools
import locale

from django import http
from django import forms
from django.conf import settings
from django.core import serializers
from django.template import loader

from EE.logic import game as game_logic
from EE.logic import game_state as game_state_logic
from EE.logic import decision as decision_logic
from EE.logic import state_mill as state_mill_logic
from EE.logic import decision_mill as decision_mill_logic

from EE.models import GameState
from EE.models import Island
from EE.models import Decision
from EE.models import Game
from EE.models import Windmill
from EE.models import StateMill
from EE.models import DecisionMill
from EE.views import handler

class BeginForm(forms.Form):
  size = forms.IntegerField(required=False)
  def __init__(self, *args, **kwargs):
    id_str = kwargs.pop('id_str', None)
    user = kwargs.pop('user', None)
    if (id_str == None):
      id_str = args[0]['id_str']
      user = args[0]['user']
    super(BeginForm, self).__init__(*args, **kwargs)
    # dynamic fields here ...
    self.fields['sizeOld'] = forms.IntegerField()
    #else:
    mills = list(game_logic.getMills(Game.objects.filter(id=id_str).get()))    
    iTeller = 1
    locale.setlocale(locale.LC_ALL, '')
	
    game_state = game_state_logic.getState(user)
    decision = decision_logic.getDecision(game_state)
    decision_mills = decision_mill_logic.getDecisionMill(decision)
    state_mills = list(state_mill_logic.getStateMills(game_state))
	
    if game_state.round >= 1:
      self.fields['size'].widget.attrs['disabled'] = 'disabled'
	
    for dm in decision_mills:
      m = dm.typeOfMill
      try:
        cost = str(locale.currency(m.cost, symbol=False, grouping=True))
      except ValueError:
        cost = m.cost
      self.fields['windmill'+str(iTeller)] = forms.CharField(initial=m.name, required=False)
      self.fields['windmill'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['windmillName'+str(iTeller)] = forms.CharField(initial=m.name)
      self.fields['number'+str(iTeller)] = forms.IntegerField(initial=(dm.noOfMills+dm.noOfMills1Month+dm.noOfMills2Months+dm.noOfMills3Months), required=False)
      self.fields['numberOriginal'+str(iTeller)] = forms.IntegerField(initial=(dm.noOfMills+dm.noOfMills1Month+dm.noOfMills2Months), required=False)
      self.fields['numberOriginal'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['numberNew'+str(iTeller)] = forms.IntegerField(initial=dm.noOfMills3Months)
      self.fields['maintenance'+str(iTeller)] = forms.IntegerField(initial=dm.noOfMaintenance)
      self.fields['maintenanceOld'+str(iTeller)] = forms.IntegerField(initial=dm.noOfMaintenance, required=False)
      self.fields['maintenanceOld'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['capacity'+str(iTeller)] = forms.IntegerField(initial=m.capacity, required=False)
      self.fields['capacity'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['costShow'+str(iTeller)] = forms.CharField(initial='EUR '+str(cost), required=False)
      self.fields['costShow'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['costReal'+str(iTeller)] = forms.IntegerField(initial=m.cost)
      self.fields['diameter'+str(iTeller)] = forms.IntegerField(initial=m.diameter, required=False) 
      self.fields['diameter'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      iTeller = iTeller +1
      for mill in mills:
	    if mill.name == m.name:
		  ##print mill.name
		  mills.remove(mill)
		  break
      for sm in state_mills:
	    if sm.typeOfMill.name == m.name:
		  state_mills.remove(sm)
		  break		
    for sm in state_mills:
      m = sm.typeOfMill
      try:
        cost = str(locale.currency(m.cost, symbol=False, grouping=True))
      except ValueError:
        cost = m.cost
      self.fields['windmill'+str(iTeller)] = forms.CharField(initial=m.name, required=False)
      self.fields['windmill'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['windmillName'+str(iTeller)] = forms.CharField(initial=m.name)
      self.fields['number'+str(iTeller)] = forms.IntegerField(initial=(sm.noOfMills+sm.noOfMills1Month+sm.noOfMills2Months+sm.noOfMills3Months), required=False)
      self.fields['numberOriginal'+str(iTeller)] = forms.IntegerField(initial=(sm.noOfMills+sm.noOfMills1Month+sm.noOfMills2Months), required=False)
      self.fields['numberOriginal'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['numberNew'+str(iTeller)] = forms.IntegerField(initial=sm.noOfMills3Months)
      self.fields['maintenance'+str(iTeller)] = forms.IntegerField(initial=dm.noOfMaintenance)
      self.fields['maintenanceOld'+str(iTeller)] = forms.IntegerField(initial=dm.noOfMaintenance, required=False)
      self.fields['maintenanceOld'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['capacity'+str(iTeller)] = forms.IntegerField(initial=m.capacity, required=False)
      self.fields['capacity'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['costShow'+str(iTeller)] = forms.CharField(initial='EUR '+str(cost), required=False)
      self.fields['costShow'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['costReal'+str(iTeller)] = forms.IntegerField(initial=m.cost)
      self.fields['diameter'+str(iTeller)] = forms.IntegerField(initial=m.diameter, required=False) 
      self.fields['diameter'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      iTeller = iTeller +1
      for mill in mills:
	    if mill.name == m.name:
		  ##print mill.name
		  mills.remove(mill)
		  break		  
    for m in mills:
      try:
        cost = str(locale.currency(m.cost, symbol=False, grouping=True))
      except ValueError:
        cost = m.cost
      self.fields['windmill'+str(iTeller)] = forms.CharField(initial=m.name, required=False)
      self.fields['windmill'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['windmillName'+str(iTeller)] = forms.CharField(initial=m.name)
      self.fields['number'+str(iTeller)] = forms.IntegerField(initial=0, required=False)
      self.fields['numberOriginal'+str(iTeller)] = forms.IntegerField(initial=0, required=False)
      self.fields['numberOriginal'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['numberNew'+str(iTeller)] = forms.IntegerField(initial=0)
      self.fields['maintenance'+str(iTeller)] = forms.IntegerField(initial=dm.noOfMaintenance)
      self.fields['maintenanceOld'+str(iTeller)] = forms.IntegerField(initial=dm.noOfMaintenance, required=False)
      self.fields['maintenanceOld'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['capacity'+str(iTeller)] = forms.IntegerField(initial=m.capacity, required=False)
      self.fields['capacity'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['costShow'+str(iTeller)] = forms.CharField(initial='EUR '+str(cost), required=False)
      self.fields['costShow'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      self.fields['costReal'+str(iTeller)] = forms.IntegerField(initial=m.cost)
      self.fields['diameter'+str(iTeller)] = forms.IntegerField(initial=m.diameter, required=False) 
      self.fields['diameter'+str(iTeller)].widget.attrs['disabled'] = 'disabled'
      iTeller = iTeller +1
  
  #windmills = forms.IntegerField()
  balance_view = forms.IntegerField()
  balance = forms.IntegerField(required=False)
  debt_view = forms.IntegerField()
  debt = forms.IntegerField(required=False)
  
class EndForm(forms.Form):
  def __init__(self, *args, **kwargs):
    ref_user = kwargs.pop('user', None)
    if (ref_user == None):
      ref_user = args[0]['user']
    super(EndForm, self).__init__(*args, **kwargs)
    #print ref_user.get_profile().gameControl.all()
    self.fields['game'] = forms.ModelMultipleChoiceField(ref_user.get_profile().gameControl.all())
    #self.fields['round'] = forms.IntegerField()

class New(handler.Handler):
  def authenticated(self):
    game = self.kwargs['id_str']
    return self.profile and game in [i.id for i in self.profile.gamePlay.all()]
	
  def getGetForm(self):
    id_str = self.kwargs['id_str']
    user = self.user
    return BeginForm(id_str=id_str, user=user)

  def getPostForm(self):
    id_str = self.kwargs['id_str']
    self.POST['id_str'] = id_str
    self.POST['user'] = self.user
    return BeginForm(self.POST)

  def post(self):
    context = self.getContext()
	
    size = self.cleaned_data['size']
    #mills = self.cleaned_data['windmills']
    balance = self.cleaned_data['balance_view']
    debt = self.cleaned_data['debt_view']
    id_str = self.kwargs['id_str']
	
    game_state = game_state_logic.getState(self.user)
	
    cost = game_state.balance - balance
	
    dec_mills = decision_mill_logic.getDecisionMill(decision_logic.getDecision(game_state))
    state_mills = list(state_mill_logic.getStateMills(game_state))
    active_mills = list(game_logic.getMills(game_logic.getGame(self.user)))
    mills = []
    iTeller = 1
    for dm in dec_mills:
	  mills.append((self.cleaned_data['windmillName'+str(iTeller)], self.cleaned_data['numberNew'+str(iTeller)], self.cleaned_data['maintenance'+str(iTeller)]))
	  iTeller = iTeller + 1
	  for m in active_mills:
	    if dm.typeOfMill.name == m.name:
		  active_mills.remove(m)
		  break
	  for sm in state_mills:
	    if dm.typeOfMill.name == sm.typeOfMill.name:
		  state_mills.remove(sm)
		  break
    for sm in state_mills:
	  mills.append((self.cleaned_data['windmillName'+str(iTeller)], self.cleaned_data['numberNew'+str(iTeller)], self.cleaned_data['maintenance'+str(iTeller)]))
	  iTeller = iTeller + 1
	  for m in active_mills:
	    if sm.typeOfMill.name == m.name:
		  active_mills.remove(m)
		  break
    for m in active_mills:
      mills.append((self.cleaned_data['windmillName'+str(iTeller)], self.cleaned_data['numberNew'+str(iTeller)], self.cleaned_data['maintenance'+str(iTeller)]))	
      iTeller = iTeller + 1	  

    arr = game_state_logic.handle_made_turn(size, mills, balance, debt, game_state, cost)
    new_state = arr[0]
    island = arr[1]
    decision = arr[2]
	
    context['balance'] = new_state.balance
    context['debt'] = new_state.debt
    context['capacity'] = island.capacity
	
    content = loader.render_to_string('round/home.html', dictionary=context)

    return http.HttpResponseRedirect('../home/' + self.kwargs['id_str'])

  def get(self):
    context = self.getContext()
    try:
	  gamestate = game_state_logic.getState(self.user)
	  island = game_state_logic.getIsland(gamestate)
	  mills = game_logic.getMills(game_logic.getGame(self.user))
	  context['numberOfMills'] = mills.count()
	  context['capacity'] = island.capacity
	  try:
		decision = decision_logic.getDecision(gamestate)
        #context['windmills'] = decision.noOfMills
        #state_mills = state_mill_logic.getStateMills(gamestate)
        #iTeller = 1
        #for mill in state_mills:
		#  context['windmills'+str(iTeller)] = mill.noOfMills
		#  iTeller = iTeller + 1
		#context['windmills'] = 0
		context['balance'] = decision.balance
		context['debt'] = decision.debt
	  except Decision.DoesNotExist:
		context['windmills'] = 0
    except GameState.DoesNotExist:
      context['balance'] = 50000000
      context['debt'] = 0
      context['capacity'] = 0
      context['windmills'] = 0
    context['id_str'] = self.kwargs['id_str']
    content = loader.render_to_string('round/new.html', dictionary=context)
    return http.HttpResponse(content)

class Home(handler.Handler):

  def authenticated(self):
    game = self.kwargs['id_str']
    return self.profile and game in [i.id for i in self.profile.gamePlay.all()]

  def get(self):
    context = self.getContext()
    id_str = self.kwargs['id_str']
	
    game = Game.objects.filter(id=id_str).get()
	
    try:
	  game_state = game_state_logic.getState(self.user)
    except GameState.DoesNotExist:
	  game_state = game_state_logic.createNew(self.user)
	 
    try:
	  decision = decision_logic.getDecision(game_state)
    except Decision.DoesNotExist:
	  decision = decision_logic.createNew(game_state, 0, 0)
	
    locale.setlocale(locale.LC_ALL, '')
	
    try:  
      balance = str(locale.currency(decision.balance, symbol=False, grouping=True))
      debt = str(locale.currency(decision.debt, symbol=False, grouping=True))
    except ValueError:
	  balance = decision.balance
	  debt = decision.debt
	
    context['balance'] = 'EUR '+balance
    context['debt'] = 'EUR '+debt
    
#    try:
#      state_mills = state_mill_logic.getStateMills(game_state)
#      if (len(state_mills) == 0):
#        state_mills = state_mill_logic.createNew(game_state, 0, game_logic.getMills(game))
#    except StateMill.DoesNotExist:
#      state_mills = state_mill_logic.createNew(game_state, 0, game_logic.getMills(game))    
	
#    context['mills'] = state_mills
	
    try:
      decision_mills = decision_mill_logic.getDecisionMill(decision)
    except DecisionMill.DoesNotExist:
      mills = game_logic.getMills(game)
      arr = []
      for m in mills:
        arr.append((0, m))
      decision_mill = decision_mill_logic.createNew(decision, arr)
	  
    context['dec_mills'] = decision_mills
			
    content = loader.render_to_string('round/home.html', dictionary=context)
	
    return http.HttpResponse(content)
	
class End(handler.Handler):
  def authenticated(self):
    game = self.kwargs['id_str']
    return self.profile and game in [i.id for i in self.profile.gameControl.all()]

  def getGetForm(self):
    ref_user = self.user
    return EndForm(user=ref_user)

  def getPostForm(self):
    ref_user = self.user
    self.POST['user'] = ref_user
    return EndForm(self.POST)

  def get(self):
    context = self.getContext()
    context['id_str'] = self.kwargs['id_str']
    game = Game.objects.filter(id=self.kwargs['id_str']).get()
    context['round'] = game.turn
    context['game'] = game
    content = loader.render_to_string('round/end.html', dictionary=context)
	
    return http.HttpResponse(content)
	
  def post(self):
    context = self.getContext()
    games = self.cleaned_data.get('game', [])
    id_str = self.kwargs['id_str']
    for game in games:
	  game_state_logic.handle_end_round(game)
	  game_logic.handle_end_round(game)
	  game_state_logic.create_new_states(game)
    return http.HttpResponseRedirect(self.BASE_PATH + 'game/home')
